import axios from "axios"
import { ElMessage } from "element-plus"
import { useTokenStore } from '@/stores'

const request = axios.create({
	baseURL: import.meta.env.VITE_SERVER_URL,
	timeout: 10000,
	withCredentials: true,
})

request.interceptors.request.use(config => {
	const { getToken } = useTokenStore()
	const token = getToken()
	if (token.length > 0) {
		config.headers.token = token
	}
	return config
})

request.interceptors.response.use(res => {
	return res.data
}, err => {
	let message;
	const status = err.response.status
	switch (status) {
		case 403:
			message = '没有访问权限'
			break
		case 404:
			message = '访问的地址不存在'
			break
		case 500:
			message = '服务器在摸鱼'
			break
		default:
			message = '出现了未知的问题'
			break
	}
	ElMessage.error(message)
	return Promise.reject(err)
})